package com.zhima.service.impl;

import com.zhima.exception.ZhimaOjException;
import com.zhima.properties.OjMailProperties;
import com.zhima.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import static com.zhima.exception.ErrorCode.CHECK_CODE_SEND_FAILURE;

@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private OjMailProperties ojMailProperties;

    @Override
    public boolean send(String toEmail, String content) {
        SimpleMailMessage simpleMailMessage = createSimpleMailMessage(toEmail);
        simpleMailMessage.setText(content);
        try {
            javaMailSender.send(simpleMailMessage);
            return true;
        } catch (MailException e) {
            throw new ZhimaOjException(e, CHECK_CODE_SEND_FAILURE);
        }
    }


    private SimpleMailMessage createSimpleMailMessage(String toEmailAddress) {
        SimpleMailMessage mimeMessage = new SimpleMailMessage();
        // 发送人
        mimeMessage.setFrom(ojMailProperties.getFromEmail());
        // 收信人
        mimeMessage.setTo(toEmailAddress);
        // 设置标题
        mimeMessage.setSubject(ojMailProperties.getTitle());
        return mimeMessage;
    }
}
